package controllers

import (
	"book1/models"
	beego "github.com/beego/beego/v2/server/web"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) List() {
	var allbook []models.Book
	err := models.DB.Find(&allbook).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": allbook,
		}
		c.ServeJSON()
		return
	}
}
func (c *BookController) Add() {
	name := c.GetString("name")
	studentid, _ := c.GetInt("student_id")
	bookname := c.GetString("bookname")
	time := c.GetString("time")
	yes := c.GetString("yes")
	bookid, _ := c.GetInt("book_id")
	allbook := models.Book{
		Name:      name,
		StudentId: studentid,
		BookName:  bookname,
		Time:      time,
		Yes:       yes,
		BookId:    bookid,
	}
	err := models.DB.Create(&allbook).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *BookController) Up() {
	name := c.GetString("name")
	studentid, _ := c.GetInt("student_id")
	bookname := c.GetString("bookname")
	time := c.GetString("time")
	yes := c.GetString("yes")
	bookid, _ := c.GetInt("book_id")
	allbook := models.Book{
		Name:      name,
		StudentId: studentid,
		BookName:  bookname,
		Time:      time,
		Yes:       yes,
		BookId:    bookid,
	}
	err := models.DB.Save(&allbook).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "修改失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "修改成功",
			"data": nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *BookController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Book{}, id).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "删除失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "删除成功",
			"data": nil,
		}
		c.ServeJSON()
		return
	}
}
